package com.zhy.usercenter.auth;

import com.zhy.usercenter.common.ErrorCode;
import com.zhy.usercenter.entity.User;
import com.zhy.usercenter.exception.BusinessException;
import com.zhy.usercenter.service.UserService;
import lombok.extern.apachecommons.CommonsLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

import static com.zhy.usercenter.constant.UserConstant.ADMIN_ROLE;
import static com.zhy.usercenter.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @author 随缘而愈
 * @version 1.0
 * @description 用户权限校验
 * @date 18/3/2024 上午11:55
 */
@Aspect
@Component
public class DbmAuthorityAspect {
    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private HttpServletRequest request;

    @Pointcut("@annotation(com.zhy.usercenter.auth.DbmAuthority)")
    public void authorityCheckPointcut(JoinPoint joinPoint) {
    }

    @Before("@annotation(com.zhy.usercenter.auth.DbmAuthority)")
    public void checkDbmAuthority(JoinPoint joinPoint) {
        try {
            // 获取当前用户的ID（从Redis中获取）
            // 根据用户ID查询用户信息
            // 获取注解类对象


            Signature signature = joinPoint.getSignature();
            MethodSignature methodSignature = (MethodSignature) signature;
            Method method = methodSignature.getMethod();
            DbmAuthority annotation = method.getAnnotation(DbmAuthority.class);
            // 检查用户是否具有所需的角色和权限
            if (isAdmin(request)) {
                // 用户具有权限，允许访问
            } else {
                throw new BusinessException(ErrorCode.NO_AUTH);
            }
        } catch (Exception ex) {
            throw new RuntimeException("权限处理异常");
        }
    }


    /**
     * 是否为管理员
     *
     * @param request   请求
     * @return          是否成功
     */
    private boolean isAdmin(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return user != null && user.getUserRole() == ADMIN_ROLE;
    }

}
